home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 2001 May / SGI Freeware 2001 May - Disc 3.iso / dist / fw_elisp-intro.idb / usr / freeware / info / emacs-lisp-intro.info-8.z / emacs-lisp-intro.info-8
Encoding:
GNU Info File  |  1998-10-28  |  45.3 KB  |  1,119 lines

  1. This is Info file emacs-lisp-intro.info, produced by Makeinfo version
  2. 1.67 from the input file emacs-lisp-intro.texi.
  3.  
  4.    This is an introduction to `Programming in Emacs Lisp', for people
  5. who are not programmers.
  6.  
  7.    Edition 1.05, 21 October 1997
  8.  
  9.    Copyright (C) 1990, '91, '92, '93, '94, '95, '97 Free Software
  10. Foundation, Inc.
  11.  
  12.    Permission is granted to make and distribute verbatim copies of this
  13. manual provided the copyright notice and this permission notice are
  14. preserved on all copies.
  15.  
  16.    Permission is granted to copy and distribute modified versions of
  17. this manual under the conditions for verbatim copying, provided also
  18. that the sections entitled "Copying" and "GNU General Public License"
  19. are included exactly as in the original, and provided that the entire
  20. resulting derived work is distributed under the terms of a permission
  21. notice identical to this one.
  22.  
  23.    Permission is granted to copy and distribute translations of this
  24. manual into another language, under the above conditions for modified
  25. versions, except that this permission notice may be stated in a
  26. translation approved by the Free Software Foundation.
  27.  
  28. 
  29. File: emacs-lisp-intro.info,  Node: re-search-forward,  Next: forward-sentence,  Prev: sentence-end,  Up: Regexp Search
  30.  
  31. The `re-search-forward' Function
  32. ================================
  33.  
  34.    The `re-search-forward' function is very like the `search-forward'
  35. function.  (*Note The `search-forward' Function: search-forward.)
  36.  
  37.    `re-search-forward' searches for a regular expression.  If the
  38. search is successful, it leaves point immediately after the last
  39. character in the target.  If the search is backwards, it leaves point
  40. just before the first character in the target.  You may tell
  41. `re-search-forward' to return `t' for true.  (Moving point is therefore
  42. a `side effect'.)
  43.  
  44.    Like `search-forward', the `re-search-forward' function takes four
  45. arguments:
  46.  
  47.   1. The first argument is the regular expression that the function
  48.      searches for.  The regular expression will be a string between
  49.      quotations marks.
  50.  
  51.   2. The optional second argument limits how far the function will
  52.      search; it is a bound, specified as a position in the buffer.
  53.  
  54.   3. The optional third argument specifies how the function responds to
  55.      failure: `nil' as the third argument causes the function to signal
  56.      an error (and print a message) when the search fails; any other
  57.      value causes it to return `nil' if the search fails and `t' if the
  58.      search succeeds.
  59.  
  60.   4. The optional fourth argument is the repeat count.  A negative
  61.      repeat count causes `re-search-forward' to search backwards.
  62.  
  63.    The template for `re-search-forward' looks like this:
  64.  
  65.      (re-search-forward "REGULAR-EXPRESSION"
  66.                      LIMIT-OF-SEARCH
  67.                      WHAT-TO-DO-IF-SEARCH-FAILS
  68.                      REPEAT-COUNT)
  69.  
  70.    The second, third, and fourth arguments are optional.  However, if
  71. you want to pass a value to either or both of the last two arguments,
  72. you must also pass a value to all the preceding arguments.  Otherwise,
  73. the Lisp interpreter will mistake which argument you are passing the
  74. value to.
  75.  
  76.    In the `forward-sentence' function, the regular expression will be
  77. the value of the variable `sentence-end', namely:
  78.  
  79.      "[.?!][]\"')}]*\\($\\|  \\|  \\)[
  80.      ]*"
  81.  
  82. The limit of the search will be the end of the paragraph (since a
  83. sentence cannot go beyond a paragraph).  If the search fails, the
  84. function will return `nil'; and the repeat count will be provided by
  85. the argument to the `forward-sentence' function.
  86.  
  87. 
  88. File: emacs-lisp-intro.info,  Node: forward-sentence,  Next: forward-paragraph,  Prev: re-search-forward,  Up: Regexp Search
  89.  
  90. `forward-sentence'
  91. ==================
  92.  
  93.    The command to move the cursor forward a sentence is a
  94. straightforward illustration of how to use regular expression searches
  95. in Emacs Lisp.  Indeed, the function looks longer and more complicated
  96. than it is; this is because the function is designed to go backwards as
  97. well as forwards; and, optionally, over more than one sentence.  The
  98. function is usually bound to the key command `M-e'.
  99.  
  100.    Here is the code for `forward-sentence':
  101.  
  102.      (defun forward-sentence (&optional arg)
  103.        "Move forward to next sentence-end.  With argument, repeat.
  104.      With negative argument, move backward repeatedly to sentence-beginning.
  105.      Sentence ends are identified by the value of sentence-end
  106.      treated as a regular expression.  Also, every paragraph boundary
  107.      terminates sentences as well."
  108.  
  109.      (interactive "p")
  110.        (or arg (setq arg 1))
  111.        (while (< arg 0)
  112.          (let ((par-beg
  113.                 (save-excursion (start-of-paragraph-text) (point))))
  114.            (if (re-search-backward
  115.                 (concat sentence-end "[^ \t\n]") par-beg t)
  116.                (goto-char (1- (match-end 0)))
  117.              (goto-char par-beg)))
  118.          (setq arg (1+ arg)))
  119.        (while (> arg 0)
  120.          (let ((par-end
  121.                 (save-excursion (end-of-paragraph-text) (point))))
  122.            (if (re-search-forward sentence-end par-end t)
  123.                (skip-chars-backward " \t\n")
  124.              (goto-char par-end)))
  125.          (setq arg (1- arg))))
  126.  
  127.    The function looks long at first sight and it is best to look at its
  128. skeleton first, and then its muscle.  The way to see the skeleton is to
  129. look at the expressions that start in the left-most columns:
  130.  
  131.      (defun forward-sentence (&optional arg)
  132.        "DOCUMENTATION..."
  133.        (interactive "p")
  134.        (or arg (setq arg 1))
  135.        (while (< arg 0)
  136.          BODY-OF-WHILE-LOOP
  137.        (while (> arg 0)
  138.          BODY-OF-WHILE-LOOP
  139.  
  140.    This looks much simpler!  The function definition consists of
  141. documentation, an `interactive' expression, an `or' expression, and
  142. `while' loops.
  143.  
  144.    Let's look at each of these parts in turn.
  145.  
  146.    We note that the documentation is thorough and understandable.
  147.  
  148.    The function has an `interactive "p"' declaration.  This means that
  149. the processed prefix argument, if any, is passed to the function as its
  150. argument.  (This will be a number.)  If the function is not passed an
  151. argument (it is optional) then the argument `arg' will be bound to 1.
  152. When `forward-sentence' is called non-interactively without an
  153. argument, `arg' is bound to `nil'.
  154.  
  155.    The `or' expression handles the prefix argument.  What it does is
  156. either leave the value of `arg' as it is, but only if `arg' is bound to
  157. a value; or it sets the value of `arg' to 1, in the case when `arg' is
  158. bound to `nil'.
  159.  
  160. * Menu:
  161.  
  162. * fwd-sentence while loops::    Two `while' loops.
  163. * fwd-sentence re-search::      A regular expression search.
  164.  
  165. 
  166. File: emacs-lisp-intro.info,  Node: fwd-sentence while loops,  Next: fwd-sentence re-search,  Prev: forward-sentence,  Up: forward-sentence
  167.  
  168. The `while' loops
  169. .................
  170.  
  171.    Two `while' loops follow the `or' expression.  The first `while' has
  172. a true-or-false-test that tests true if the prefix argument for
  173. `forward-sentence' is a negative number.  This is for going backwards.
  174. The body of this loop is similar to the body of the second `while'
  175. clause, but it is not exactly the same.  We will skip this `while' loop
  176. and concentrate on the second `while' loop.
  177.  
  178.    The second `while' loop is for moving point forward.  Its skeleton
  179. looks like this:
  180.  
  181.      (while (> arg 0)            ; true-or-false-test
  182.        (let VARLIST
  183.          (if (TRUE-OR-FALSE-TEST)
  184.              THEN-PART
  185.            ELSE-PART
  186.        (setq arg (1- arg))))     ; `while' loop decrementer
  187.  
  188.    The `while' loop is of the decrementing kind.  (*Note A Loop with a
  189. Decrementing Counter: Decrementing Loop.)  It has a true-or-false-test
  190. that tests true so long as the counter (in this case, the variable
  191. `arg') is greater than zero; and it has a decrementer that subtracts 1
  192. from the value of the counter every time the loop repeats.
  193.  
  194.    If no prefix argument is given to `forward-sentence', which is the
  195. most common way the command is used, this `while' loop will run once,
  196. since the value of `arg' will be 1.
  197.  
  198.    The body of the `while' loop consists of a `let' expression, which
  199. creates and binds a local variable, and has, as its body, an `if'
  200. expression.
  201.  
  202.    The body of the `while' loop looks like this:
  203.  
  204.      (let ((par-end
  205.             (save-excursion (end-of-paragraph-text) (point))))
  206.        (if (re-search-forward sentence-end par-end t)
  207.            (skip-chars-backward " \t\n")
  208.          (goto-char par-end)))
  209.  
  210.    The `let' expression creates and binds the local variable `par-end'.
  211. As we shall see, this local variable is designed to provide a bound or
  212. limit to the regular expression search.  If the search fails to find a
  213. proper sentence ending in the paragraph, it will stop on reaching the
  214. end of the paragraph.
  215.  
  216.    But first, let us examine how `par-end' is bound to the value of the
  217. end of the paragraph.  What happens is that the `let' sets the value of
  218. `par-end' to the value returned when the Lisp interpreter evaluates the
  219. expression
  220.  
  221.      (save-excursion (end-of-paragraph-text) (point))
  222.  
  223. In this expression, `(end-of-paragraph-text)' moves point to the end of
  224. the paragraph, `(point)' returns the value of point, and then
  225. `save-excursion' restores point to its original position.  Thus, the
  226. `let' binds `par-end' to the value returned by the `save-excursion'
  227. expression, which is the position of the end of the paragraph.  (The
  228. `(end-of-paragraph-text)' function uses `forward-paragraph', which we
  229. will discuss shortly.)
  230.  
  231.    Emacs next evaluates the body of the `let', which is an `if'
  232. expression that looks like this:
  233.  
  234.      (if (re-search-forward sentence-end par-end t) ; if-part
  235.          (skip-chars-backward " \t\n")              ; then-part
  236.        (goto-char par-end)))                        ; else-part
  237.  
  238.    The `if' tests whether its first argument is true and if so,
  239. evaluates its then-part; otherwise, the Emacs Lisp interpreter
  240. evaluates the else-part.  The true-or-false-test of the `if' expression
  241. is the regular expression search.
  242.  
  243.    It may seem odd to have what looks like the `real work' of the
  244. `forward-sentence' function buried here, but this is a common way this
  245. kind of operation is carried out in Lisp.
  246.  
  247. 
  248. File: emacs-lisp-intro.info,  Node: fwd-sentence re-search,  Prev: fwd-sentence while loops,  Up: forward-sentence
  249.  
  250. The regular expression search
  251. .............................
  252.  
  253.    The `re-search-forward' function searches for the end of the
  254. sentence, that is, for the pattern defined by the `sentence-end'
  255. regular expression.  If the pattern is found--if the end of the
  256. sentence is found--then the `re-search-forward' function does two
  257. things:
  258.  
  259.   1. The `re-search-forward' function carries out a side effect, which
  260.      is to move point to the end of the occurrence found.
  261.  
  262.   2. The `re-search-forward' function returns a value of true.  This is
  263.      the value received by the `if', and means that the search was
  264.      successful.
  265.  
  266. The side effect, the movement of point, is completed before the `if'
  267. function is handed the value returned by the successful conclusion of
  268. the search.
  269.  
  270.    When the `if' function receives the value of true from a successful
  271. call to `re-search-forward', the `if' evaluates the then-part, which is
  272. the expression `(skip-chars-backward " \t\n")'.  This expression moves
  273. backwards over any blank spaces, tabs or carriage returns until a
  274. printed character is found and then leaves point after the character.
  275. Since point has already been moved to the end of the pattern that marks
  276. the end of the sentence, this action leaves point right after the
  277. closing printed character of the sentence, which is usually a period.
  278.  
  279.    On the other hand, if the `re-search-forward' function fails to find
  280. a pattern marking the end of the sentence, the function returns false.
  281. The false then causes the `if' to evaluate its third argument, which is
  282. `(goto-char par-end)':  it moves point to the end of the paragraph.
  283.  
  284.    Regular expression searches are exceptionally useful and the pattern
  285. illustrated by `re-search-forward', in which the search is the test of
  286. an `if' expression, is handy.  You will see or write code incorporating
  287. this pattern often.
  288.  
  289. 
  290. File: emacs-lisp-intro.info,  Node: forward-paragraph,  Next: etags,  Prev: forward-sentence,  Up: Regexp Search
  291.  
  292. `forward-paragraph': a Goldmine of Functions
  293. ============================================
  294.  
  295.    The `forward-paragraph' function moves point forward to the end of
  296. the paragraph.  It is usually bound to `M-}' and makes use of a number
  297. of functions that are important in themselves, including `let*',
  298. `match-beginning', and `looking-at'.
  299.  
  300.    The function definition for `forward-paragraph' is considerably
  301. longer than the function definition for `forward-sentence' because it
  302. works with a paragraph, each line of which may begin with a fill prefix.
  303.  
  304.    A fill prefix consists of a string of characters that are repeated at
  305. the beginning of each line.  For example, in Lisp code, it is a
  306. convention to start each line of a paragraph-long comment with `;;; '.
  307. In Text mode, four blank spaces make up another common fill prefix,
  308. creating an indented paragraph.  (*Note Fill Prefix: (emacs)Fill
  309. Prefix, for more information about fill prefixes.)
  310.  
  311.    The existence of a fill prefix means that in addition to being able
  312. to find the end of a paragraph whose lines begin on the left-most
  313. column, the `forward-paragraph' function must be able to find the end
  314. of a paragraph when all or many of the lines in the buffer begin with
  315. the fill prefix.
  316.  
  317.    Moreover, it is sometimes practical to ignore a fill prefix that
  318. exists, especially when blank lines separate paragraphs.  This is an
  319. added complication.
  320.  
  321.    Rather than print all of the `forward-paragraph' function, we will
  322. only print parts of it.  Read without preparation, the function can be
  323. daunting!
  324.  
  325.    In outline, the function looks like this:
  326.  
  327.      (defun forward-paragraph (&optional arg)
  328.        "DOCUMENTATION..."
  329.        (interactive "p")
  330.        (or arg (setq arg 1))
  331.        (let*
  332.            VARLIST
  333.          (while (< arg 0)        ; backward-moving-code
  334.            ...
  335.            (setq arg (1+ arg)))
  336.          (while (> arg 0)        ; forward-moving-code
  337.            ...
  338.            (setq arg (1- arg)))))
  339.  
  340.    The first parts of the function are routine: the function's argument
  341. list consists of one optional argument.  Documentation follows.
  342.  
  343.    The lower case `p' in the `interactive' declaration means that the
  344. processed prefix argument, if any, is passed to the function.  This
  345. will be a number, and is the repeat count of how many paragraphs point
  346. will move.  The `or' expression in the next line handles the common
  347. case when no argument is passed to the function, which occurs if the
  348. function is called from other code rather than interactively.  This
  349. case was described earlier.  (*Note The `forward-sentence' function:
  350. forward-sentence.)  Now we reach the end of the familiar part of this
  351. function.
  352.  
  353. * Menu:
  354.  
  355. * fwd-para let::                The `let*' expression.
  356. * fwd-para while::              The forward motion `while' loop.
  357. * fwd-para between paragraphs::  Movement between paragraphs.
  358. * fwd-para within paragraph::   Movement within paragraphs.
  359. * fwd-para no fill prefix::     When there is no fill prefix.
  360. * fwd-para with fill prefix::   When there is a fill prefix.
  361. * fwd-para summary::            Summary of `forward-paragraph' code.
  362.  
  363. 
  364. File: emacs-lisp-intro.info,  Node: fwd-para let,  Next: fwd-para while,  Prev: forward-paragraph,  Up: forward-paragraph
  365.  
  366. The `let*' expression
  367. .....................
  368.  
  369.    The next line of the `forward-paragraph' function begins a `let*'
  370. expression.  This is a different kind of expression than we have seen
  371. so far.  The symbol is `let*' not `let'.
  372.  
  373.    The `let*' special form is like `let' except that Emacs sets each
  374. variable in sequence, one after another, and variables in the latter
  375. part of the varlist can make use of the values to which Emacs set
  376. variables in the earlier part of the varlist.
  377.  
  378.    In the `let*' expression in this function, Emacs binds two
  379. variables: `fill-prefix-regexp' and `paragraph-separate'.  The value to
  380. which `paragraph-separate' is bound depends on the value of
  381. `fill-prefix-regexp'.
  382.  
  383.    Let's look at each in turn.  The symbol `fill-prefix-regexp' is set
  384. to the value returned by evaluating the following list:
  385.  
  386.      (and fill-prefix
  387.           (not (equal fill-prefix ""))
  388.           (not paragraph-ignore-fill-prefix)
  389.           (regexp-quote fill-prefix))
  390.  
  391. This is an expression whose first element is the function `and'.
  392.  
  393.    The `and' function evaluates each of its arguments until one of the
  394. arguments returns a value of `nil', in which case the `and' expression
  395. returns `nil'; however, if none of the arguments returns a value of
  396. `nil', the value resulting from evaluating the last argument is
  397. returned.  (Since such a value is not `nil', it is considered true in
  398. Lisp.)  In other words, an `and' expression returns a true value only
  399. if all its arguments are true.
  400.  
  401.    In this case, the variable `fill-prefix-regexp' is bound to a
  402. non-`nil' value only if the following four expressions produce a true
  403. (i.e., a non-`nil') value when they are evaluated; otherwise,
  404. `fill-prefix-regexp' is bound to `nil'.
  405.  
  406. `fill-prefix'
  407.      When this variable is evaluated, the value of the fill prefix, if
  408.      any, is returned.  If there is no fill prefix, this variable
  409.      returns `nil'.
  410.  
  411. `(not (equal fill-prefix "")'
  412.      This expression checks whether an existing fill prefix is an empty
  413.      string, that is, a string with no characters in it.  An empty
  414.      string is not a useful fill prefix.
  415.  
  416. `(not paragraph-ignore-fill-prefix)'
  417.      This expression returns `nil' if the variable
  418.      `paragraph-ignore-fill-prefix' has been turned on by being set to a
  419.      true value such as `t'.
  420.  
  421. `(regexp-quote fill-prefix)'
  422.      This is the last argument to the `and' function.  If all the
  423.      arguments to the `and' are true, the value resulting from
  424.      evaluating this expression will be returned by the `and' expression
  425.      and bound to the variable `fill-prefix-regexp',
  426.  
  427. The result of evaluating this `and' expression successfully is that
  428. `fill-prefix-regexp' will be bound to the value of `fill-prefix' as
  429. modified by the `regexp-quote' function.  What `regexp-quote' does is
  430. read a string and return a regular expression that will exactly match
  431. the string and match nothing else.  This means that
  432. `fill-prefix-regexp' will be set to a value that will exactly match the
  433. fill prefix if the fill prefix exists.  Otherwise, the variable will be
  434. set to `nil'.
  435.  
  436.    The second local variable in the `let*' expression is
  437. `paragraph-separate'.  It is bound to the value returned by evaluating
  438. the expression:
  439.  
  440.      (if fill-prefix-regexp
  441.          (concat paragraph-separate
  442.                  "\\|^" fill-prefix-regexp "[ \t]*$")
  443.        paragraph-separate)))
  444.  
  445.    This expression shows why `let*' rather than `let' was used.  The
  446. true-or-false-test for the `if' depends on whether the variable
  447. `fill-prefix-regexp' evaluates to `nil' or some other value.
  448.  
  449.    If `fill-prefix-regexp' does not have a value, Emacs evaluates the
  450. else-part of the `if' expression and binds `paragraph-separate' to its
  451. local value.  (`paragraph-separate' is a regular expression that
  452. matches what separates paragraphs.)
  453.  
  454.    But if `fill-prefix-regexp' does have a value, Emacs evaluates the
  455. then-part of the `if' expression and binds `paragraph-separate' to a
  456. regular expression that includes the `fill-prefix-regexp' as part of
  457. the pattern.
  458.  
  459.    Specifically, `paragraph-separate' is set to the original value of
  460. the paragraph separate regular expression concatenated with an
  461. alternative expression that consists of the `fill-prefix-regexp'
  462. followed by a blank line.  The `^' indicates that the
  463. `fill-prefix-regexp' must begin a line, and the optional whitespace to
  464. the end of the line is defined by `"[ \t]*$"'.) The `\\|' defines this
  465. portion of the regexp as an alternative to `paragraph-separate'.
  466.  
  467.    Now we get into the body of the `let*'.  The first part of the body
  468. of the `let*' deals with the case when the function is given a negative
  469. argument and is therefore moving backwards.  We will skip this section.
  470.  
  471. 
  472. File: emacs-lisp-intro.info,  Node: fwd-para while,  Next: fwd-para between paragraphs,  Prev: fwd-para let,  Up: forward-paragraph
  473.  
  474. The forward motion `while' loop
  475. ...............................
  476.  
  477.    The second part of the body of the `let*' deals with forward motion.
  478. It is a `while' loop that repeats itself so long as the value of `arg'
  479. is greater than zero.  In the most common use of the function, the
  480. value of the argument is 1, so the body of the `while' loop is
  481. evaluated exactly once, and the cursor moves forward one paragraph.
  482.  
  483.    This part handles three situations: when point is between paragraphs,
  484. when point is within a paragraph and there is a fill prefix, and when
  485. point is within a paragraph and there is no fill prefix.
  486.  
  487.    The `while' loop looks like this:
  488.  
  489.      (while (> arg 0)
  490.        (beginning-of-line)
  491.      
  492.        ;; between paragraphs
  493.        (while (prog1 (and (not (eobp))
  494.                           (looking-at paragraph-separate))
  495.                 (forward-line 1)))
  496.      
  497.        ;; within paragraphs, with a fill prefix
  498.        (if fill-prefix-regexp
  499.            ;; There is a fill prefix; it overrides paragraph-start.
  500.            (while (and (not (eobp))
  501.                        (not (looking-at paragraph-separate))
  502.                        (looking-at fill-prefix-regexp))
  503.              (forward-line 1))
  504.      
  505.          ;; within paragraphs, no fill prefix
  506.          (if (re-search-forward paragraph-start nil t)
  507.              (goto-char (match-beginning 0))
  508.            (goto-char (point-max))))
  509.      
  510.        (setq arg (1- arg)))
  511.  
  512.    We can see immediately that this is a decrementing counter `while'
  513. loop, using the expression `(setq (1- arg))' as the decrementer.  The
  514. body of the loop consists of three expressions:
  515.  
  516.      ;; between paragraphs
  517.      (beginning-of-line)
  518.      (while
  519.          BODY-OF-WHILE)
  520.      
  521.      ;; within paragraphs, with fill prefix
  522.      (if TRUE-OR-FALSE-TEST
  523.          THEN-PART
  524.      
  525.      ;; within paragraphs, no fill prefix
  526.        ELSE-PART
  527.  
  528. When the Emacs Lisp interpreter evaluates the body of the `while' loop,
  529. the first thing it does is evaluate the `(beginning-of-line)'
  530. expression and move point to the beginning of the line.  Then there is
  531. an inner `while' loop.  This `while' loop is designed to move the
  532. cursor out of the blank space between paragraphs, if it should happen
  533. to be there.  Finally there is an `if' expression that actually moves
  534. point to the end of the paragraph.
  535.  
  536. 
  537. File: emacs-lisp-intro.info,  Node: fwd-para between paragraphs,  Next: fwd-para within paragraph,  Prev: fwd-para while,  Up: forward-paragraph
  538.  
  539. Between paragraphs
  540. ..................
  541.  
  542.    First, let us look at the inner `while' loop.  This loop handles the
  543. case when point is between paragraphs; it uses three functions that are
  544. new to us: `prog1', `eobp' and `looking-at'.
  545.  
  546.    * `prog1' is similar to the `progn' function, except that `prog1'
  547.      evaluates its arguments in sequence and then returns the value of
  548.      its first argument as the value of the whole expression.  (`progn'
  549.      returns the value of its last argument as the value of the
  550.      expression.) The second and subsequent arguments to `prog1' are
  551.      evaluated only for their side effects.
  552.  
  553.    * `eobp' is an abbreviation of `End Of Buffer P' and is a function
  554.      that returns true if point is at the end of the buffer.
  555.  
  556.    * `looking-at' is a function that returns true if the text following
  557.      point matches the regular expression passed `looking-at' as its
  558.      argument.
  559.  
  560.    The `while' loop we are studying looks like this:
  561.  
  562.      (while (prog1 (and (not (eobp))
  563.                         (looking-at paragraph-separate))
  564.                    (forward-line 1)))
  565.  
  566. This is a `while' loop with no body!  The true-or-false-test of the
  567. loop is the expression:
  568.  
  569.      (prog1 (and (not (eobp))
  570.                  (looking-at paragraph-separate))
  571.             (forward-line 1)))
  572.  
  573. The first argument to the `prog1' is the `and' expression.  It has
  574. within in it a test of whether point is at the end of the buffer and
  575. also a test of whether the pattern following point matches the regular
  576. expression for separating paragraphs.
  577.  
  578.    If the cursor is not at the end of the buffer and if the characters
  579. following the cursor mark the separation between two paragraphs, then
  580. the `and' expression is true.  After evaluating the `and' expression,
  581. the Lisp interpreter evaluates the second argument to `prog1', which is
  582. `forward-line'.  This moves point forward one line.  The value returned
  583. by the `prog1' however, is the value of its first argument, so the
  584. `while' loop continues so long as point is not at the end of the buffer
  585. and is between paragraphs.  When, finally, point is moved to a
  586. paragraph, the `and' expression tests false.  Note however, that the
  587. `forward-line' command is carried out anyhow.  This means that when
  588. point is moved from between paragraphs to a paragraph, it is left at
  589. the beginning of the second line of the paragraph.
  590.  
  591. 
  592. File: emacs-lisp-intro.info,  Node: fwd-para within paragraph,  Next: fwd-para no fill prefix,  Prev: fwd-para between paragraphs,  Up: forward-paragraph
  593.  
  594. Within paragraphs
  595. .................
  596.  
  597.    The next expression in the outer `while' loop is an `if' expression.
  598. The Lisp interpreter evaluates the then-part of the `if' when the
  599. `fill-prefix-regexp' variable has a value other than `nil', and it
  600. evaluates the else-part when the value of `if fill-prefix-regexp' is
  601. `nil', that is, when there is no fill prefix.
  602.  
  603. 
  604. File: emacs-lisp-intro.info,  Node: fwd-para no fill prefix,  Next: fwd-para with fill prefix,  Prev: fwd-para within paragraph,  Up: forward-paragraph
  605.  
  606. No fill prefix
  607. ..............
  608.  
  609.    It is simplest to look at the code for the case when there is no fill
  610. prefix first.  This code consists of yet another inner `if' expression,
  611. and reads as follows:
  612.  
  613.      (if (re-search-forward paragraph-start nil t)
  614.          (goto-char (match-beginning 0))
  615.        (goto-char (point-max)))
  616.  
  617. This expression actually does the work that most people think of as the
  618. primary purpose of the `forward-paragraph' command: it causes a regular
  619. expression search to occur that searches forward to the start of the
  620. next paragraph and if it is found, moves point there; but if the start
  621. of another paragraph if not found, it moves point to the end of the
  622. accessible region of the buffer.
  623.  
  624.    The only unfamiliar part of this is the use of `match-beginning'.
  625. This is another function that is new to us.  The `match-beginning'
  626. function returns a number specifying the location of the start of the
  627. text that was matched by the last regular expression search.
  628.  
  629.    The `match-beginning' function is used here because of a
  630. characteristic of a forward search: a successful forward search,
  631. regardless of whether it is a plain search or a regular expression
  632. search, will move point to the end of the text that is found.  In this
  633. case, a successful search will move point to the end of the pattern for
  634. `paragraph-start', which will be the beginning of the next paragraph
  635. rather than the end of the current one.
  636.  
  637.    However, we want to put point at the end of the current paragraph,
  638. not at the beginning of the next one.  The two positions may be
  639. different, because there may be several blank lines between paragraphs.
  640.  
  641.    When given an argument of 0, `match-beginning' returns the position
  642. that is the start of the text that the most recent regular expression
  643. search matched.  In this case, the most recent regular expression
  644. search is the one looking for `paragraph-start', so `match-beginning'
  645. returns the beginning position of the pattern, rather than the end of
  646. the pattern.  The beginning position is the end of the paragraph.
  647.  
  648.    (Incidentally, when passed a positive number as an argument, the
  649. `match-beginning' function will place point at that parenthesized
  650. expression in the last regular expression.  It is a useful function.)
  651.  
  652. 
  653. File: emacs-lisp-intro.info,  Node: fwd-para with fill prefix,  Next: fwd-para summary,  Prev: fwd-para no fill prefix,  Up: forward-paragraph
  654.  
  655. With a fill prefix
  656. ..................
  657.  
  658.    The inner `if' expression just discussed is the else-part of an
  659. enclosing `if' expression which tests whether there is a fill prefix.
  660. If there is a fill prefix, the then-part of this `if' is evaluated.  It
  661. looks like this:
  662.  
  663.      (while (and (not (eobp))
  664.                  (not (looking-at paragraph-separate))
  665.                  (looking-at fill-prefix-regexp))
  666.        (forward-line 1))
  667.  
  668. What this expression does is move point forward line by line so long as
  669. three conditions are true:
  670.  
  671.   1. Point is not at the end of the buffer.
  672.  
  673.   2. The text following point does not separate paragraphs.
  674.  
  675.   3. The pattern following point is the fill prefix regular expression.
  676.  
  677.    The last condition may be puzzling, until you remember that point was
  678. moved to the beginning of the line early in the `forward-paragraph'
  679. function.  This means that if the text has a fill prefix, the
  680. `looking-at' function will see it.
  681.  
  682. 
  683. File: emacs-lisp-intro.info,  Node: fwd-para summary,  Prev: fwd-para with fill prefix,  Up: forward-paragraph
  684.  
  685. Summary
  686. .......
  687.  
  688.    In summary, when moving forward, the `forward-paragraph' function
  689. does the following:
  690.  
  691.    * Move point to the beginning of the line.
  692.  
  693.    * Skip over lines between paragraphs.
  694.  
  695.    * Check whether there is a fill prefix, and if there is:
  696.  
  697.         -- Go forward line by line so long as the line is not a
  698.           paragraph separating line.
  699.  
  700.    * But if there is no fill prefix,
  701.  
  702.         -- Search for the next paragraph start pattern.
  703.  
  704.         -- Go to the beginning of the paragraph start pattern, which
  705.           will be the end of the previous paragraph.
  706.  
  707.         -- Or else go to the end of the accessible portion of the
  708.           buffer.
  709.  
  710.    For review, here is the code we have just been discussing, formatted
  711. for clarity:
  712.  
  713.      (interactive "p")
  714.      (or arg (setq arg 1))
  715.      (let* (
  716.             (fill-prefix-regexp
  717.              (and fill-prefix (not (equal fill-prefix ""))
  718.                   (not paragraph-ignore-fill-prefix)
  719.                   (regexp-quote fill-prefix)))
  720.      
  721.             (paragraph-separate
  722.              (if fill-prefix-regexp
  723.                  (concat paragraph-separate
  724.                          "\\|^"
  725.                          fill-prefix-regexp
  726.                          "[ \t]*$")
  727.                paragraph-separate)))
  728.      
  729.        BACKWARD-MOVING-CODE (OMITTED) ...
  730.      
  731.        (while (> arg 0)                ; forward-moving-code
  732.          (beginning-of-line)
  733.      
  734.          (while (prog1 (and (not (eobp))
  735.                             (looking-at paragraph-separate))
  736.                   (forward-line 1)))
  737.      
  738.          (if fill-prefix-regexp
  739.              (while (and (not (eobp))  ; then-part
  740.                          (not (looking-at paragraph-separate))
  741.                          (looking-at fill-prefix-regexp))
  742.                (forward-line 1))
  743.                                        ; else-part: the inner-if
  744.            (if (re-search-forward paragraph-start nil t)
  745.                (goto-char (match-beginning 0))
  746.              (goto-char (point-max))))
  747.      
  748.          (setq arg (1- arg)))))        ; decrementer
  749.  
  750.    The full definition for the `forward-paragraph' function not only
  751. includes this code for going forwards, but also code for going
  752. backwards.
  753.  
  754.    If you are reading this inside of GNU Emacs and you want to see the
  755. whole function, you can type `M-.' (`find-tag') and the name of the
  756. function when prompted for it.  If the `find-tag' function first asks
  757. you for the name of a `TAGS' table, give it the name of the `TAGS' file
  758. in your `emacs/src' directory, which will have a pathname such as
  759. `/usr/local/lib/emacs/19.23/src/TAGS'.  (The exact path to the
  760. `emacs/src' directory depends on how your copy of Emacs was installed.
  761. If you don't know the path, you can sometimes find out by typing `C-h
  762. i' to enter Info and then typing `C-x C-f' to see the path to the
  763. `emacs/info' directory.  The path to the `TAGS' file is often the
  764. corresponding `emacs/src' path; sometimes, however, Info files are
  765. stored elsewhere.)
  766.  
  767.    You can also create your own `TAGS' file for directories that lack
  768. one.  *Note Create Your Own `TAGS' File: etags.
  769.  
  770. 
  771. File: emacs-lisp-intro.info,  Node: etags,  Next: Regexp Review,  Prev: forward-paragraph,  Up: Regexp Search
  772.  
  773. Create Your Own `TAGS' File
  774. ===========================
  775.  
  776.    You can create your own `TAGS' file to help you jump to sources.
  777. For example, if you have a large number of files in your `~/emacs'
  778. directory, as I do--I have 137 `.el' files in it, of which I load 17--
  779. you will find it easier to jump to specific functions if you create a
  780. `TAGS' file for that directory than if you search for the function name
  781. with `grep' or some other tool.
  782.  
  783.    You can create a `TAGS' file by calling the `etags' program that
  784. comes as a part of the Emacs distribution.  Usually, `etags' is
  785. compiled and installed when Emacs is built.  (`etags' is not an Emacs
  786. Lisp function or a part of Emacs; it is a C program.)
  787.  
  788.    To create a `TAGS' file, first switch to the directory in which you
  789. want to create the file.  In Emacs you can do this with the `M-x cd'
  790. command, or by visiting a file in the directory, or by listing the
  791. directory with `C-x d' (`dired').  Then type
  792.  
  793.      M-! etags *.el
  794.  
  795. to create a `TAGS' file.  The `etags' program takes all the usual shell
  796. `wildcards'.  For example, if you have two directories for which you
  797. want a single `TAGS file', type the command like this, where
  798. `../elisp/' is the second directory:
  799.  
  800.      M-! etags  *.el ../elisp/*.el
  801.  
  802.    Type
  803.  
  804.      M-! etags --help
  805.  
  806. to see a list of the options accepted by `etags'.
  807.  
  808.    The `etags' program handles Emacs Lisp, Common Lisp, Scheme, C,
  809. Fortran, Pascal, LaTeX, and most assemblers.  The program has no
  810. switches for specifying the language; it recognizes the language in an
  811. input file according to its file name and contents.
  812.  
  813.    Also, `etags' is very helpful when you are writing code yourself and
  814. want to refer back to functions you have already written.  Just run
  815. `etags' again at intervals as you write new functions, so they become
  816. part of the `TAGS' file.
  817.  
  818. 
  819. File: emacs-lisp-intro.info,  Node: Regexp Review,  Next: re-search Exercises,  Prev: etags,  Up: Regexp Search
  820.  
  821. Review
  822. ======
  823.  
  824.    Here is a brief summary of some recently introduced functions.
  825.  
  826. `while'
  827.      Repeatedly evaluate the body of the expression so long as the first
  828.      element of the body tests true.  Then return `nil'.  (The
  829.      expression is evaluated only for its side effects.)
  830.  
  831.      For example:
  832.  
  833.           (let ((foo 2))
  834.             (while (> foo 0)
  835.               (insert (format "foo is %d.\n" foo))
  836.               (setq foo (1- foo))))
  837.           
  838.                =>       foo is 2.
  839.                        foo is 1.
  840.                        nil
  841.  
  842.      (The `insert' function inserts its arguments at point; the
  843.      `format' function returns a string formatted from its arguments
  844.      the way `message' formats its arguments; `\n' produces a new line.)
  845.  
  846. `re-search-forward'
  847.      Search for a pattern, and if the pattern is found, move point to
  848.      rest just after it.
  849.  
  850.      Takes four arguments, like `search-forward':
  851.  
  852.        1. A regular expression that specifies the pattern to search for.
  853.  
  854.        2. Optionally, the limit of the search.
  855.  
  856.        3. Optionally, what to do if the search fails, return `nil' or an
  857.           error message.
  858.  
  859.        4. Optionally, how many times to repeat the search; if negative,
  860.           the search goes backwards.
  861.  
  862. `let*'
  863.      Bind some variables locally to particular values, and then
  864.      evaluate the remaining arguments, returning the value of the last
  865.      one.  While binding the local variables, use the local values of
  866.      variables bound earlier, if any.
  867.  
  868.      For example:
  869.  
  870.           (let* ((foo 7)
  871.                 (bar (* 3 foo)))
  872.             (message "`bar' is %d." bar))
  873.                => `bar' is 21.
  874.  
  875. `match-beginning'
  876.      Return the position of the start of the text found by the last
  877.      regular expression search.
  878.  
  879. `looking-at'
  880.      Return `t' for true if the text after point matches the argument,
  881.      which should be a regular expression.
  882.  
  883. `eobp'
  884.      Return `t' for true if point is at the end of the accessible part
  885.      of a buffer.  The end of the accessible part is the end of the
  886.      buffer if the buffer is not narrowed; it is the end of the
  887.      narrowed part if the buffer is narrowed.
  888.  
  889. `prog1'
  890.      Evaluate each argument in sequence and then return the value of the
  891.      *first*.
  892.  
  893.      For example:
  894.  
  895.           (prog1 1 2 3 4)
  896.                => 1
  897.  
  898. 
  899. File: emacs-lisp-intro.info,  Node: re-search Exercises,  Prev: Regexp Review,  Up: Regexp Search
  900.  
  901. Exercises with `re-search-forward'
  902. ==================================
  903.  
  904.    * Write a function to search for a regular expression that matches
  905.      two or more blank lines in sequence.
  906.  
  907.    * Write a function to search for duplicated words, such as `the the'.
  908.      *Note Syntax of Regular Expressions: (emacs)Regexps, for
  909.      information on how to write a regexp (a regular expression) to
  910.      match a string that is composed of two identical halves.  You can
  911.      devise several regexps; some are better than others.  The function
  912.      I use is described in an appendix, along with several regexps.
  913.      *Note `the-the' Duplicated Words Function: the-the.
  914.  
  915. 
  916. File: emacs-lisp-intro.info,  Node: Counting Words,  Next: Words in a defun,  Prev: Regexp Search,  Up: Top
  917.  
  918. Counting: Repetition and Regexps
  919. ********************************
  920.  
  921.    Repetition and regular expression searches are powerful tools that
  922. you often use when you write code in Emacs Lisp.  This chapter
  923. illustrates the use of regular expression searches through the
  924. construction of word count commands using `while' loops and recursion.
  925.  
  926. * Menu:
  927.  
  928. * Why Count Words::             Emacs lacks a word count command.
  929. * count-words-region::          Use a regexp, but find a problem.
  930. * recursive-count-words::       Start with case of no words in region.
  931. * Counting Exercise::
  932.  
  933. 
  934. File: emacs-lisp-intro.info,  Node: Why Count Words,  Next: count-words-region,  Prev: Counting Words,  Up: Counting Words
  935.  
  936. Counting words
  937. ==============
  938.  
  939.    The standard Emacs distribution contains a function for counting the
  940. number of lines within a region.  However, there is no corresponding
  941. function for counting words.
  942.  
  943.    Certain types of writing ask you to count words.  Thus, if you write
  944. an essay, you may be limited to 800 words; if you write a novel, you
  945. may discipline yourself to write 1000 words a day.  It seems odd to me
  946. that Emacs lacks a word count command.  Perhaps people use Emacs mostly
  947. for code or types of documentation that do not require word counts; or
  948. perhaps they restrict themselves to the operating system word count
  949. command, `wc'.  Alternatively, people may follow the publishers'
  950. convention and compute a word count by dividing the number of
  951. characters in a document by five.  In any event, here are commands to
  952. count words.
  953.  
  954. 
  955. File: emacs-lisp-intro.info,  Node: count-words-region,  Next: recursive-count-words,  Prev: Why Count Words,  Up: Counting Words
  956.  
  957. The `count-words-region' Function
  958. =================================
  959.  
  960.    A word count command could count words in a line, paragraph, region,
  961. or buffer.  What should the command cover?  You could design the
  962. command to count the number of words in a complete buffer.  However,
  963. the Emacs tradition encourages flexibility--you may want to count words
  964. in just a section, rather than all of a buffer.  So it makes more sense
  965. to design the command to count the number of words in a region.  Once
  966. you have a `count-words-region' command, you can, if you wish, count
  967. words in a whole buffer by marking it with `C-x h'
  968. (`mark-whole-buffer').
  969.  
  970.    Clearly, counting words is a repetitive act: starting from the
  971. beginning of the region, you count the first word, then the second
  972. word, then the third word, and so on, until you reach the end of the
  973. region.  This means that word counting is ideally suited to recursion
  974. or to a `while' loop.
  975.  
  976.    First, we will implement the word count command with a `while' loop,
  977. then with recursion.  The command will, of course, be interactive.
  978.  
  979.    The template for an interactive function definition is, as always:
  980.  
  981.      (defun NAME-OF-FUNCTION (ARGUMENT-LIST)
  982.        "DOCUMENTATION..."
  983.        (INTERACTIVE-EXPRESSION...)
  984.        BODY...)
  985.  
  986.    What we need to do is fill in the slots.
  987.  
  988.    The name of the function should be self-explanatory and similar to
  989. the existing `count-lines-region' name.  This makes the name easier to
  990. remember.  `count-words-region' is a good choice.
  991.  
  992.    The function counts words within a region.  This means that the
  993. argument list must contain symbols that are bound to the two positions,
  994. the beginning and end of the region.  These two positions can be called
  995. `beginning' and `end' respectively.  The first line of the
  996. documentation should be a single sentence, since that is all that is
  997. printed as documentation by a command such as `apropos'.  The
  998. interactive expression will be of the form `(interactive "r")', since
  999. that will cause Emacs to pass the beginning and end of the region to
  1000. the function's argument list.  All this is routine.
  1001.  
  1002.    The body of the function needs to be written so as to do three tasks:
  1003. first to set up conditions under which the `while' loop can count words,
  1004. second to run the `while' loop, and, third, to send a message to the
  1005. user.
  1006.  
  1007.    When a user calls `count-words-region', point may be at the
  1008. beginning or the end of the region.  However, the counting process must
  1009. start at the beginning of the region.  This means we will want to put
  1010. point there if it is not already there.  Executing `(goto-char
  1011. beginning)' ensures this.  Of course, we will want to return point to
  1012. its expected position when the function finishes its work.  For this
  1013. reason, the body must be enclosed in a `save-excursion' expression.
  1014.  
  1015.    The central part of the body of the function consists of a `while'
  1016. loop in which one expression jumps point forward word by word, and
  1017. another expression counts those jumps.  The true-or-false-test of the
  1018. `while' loop should test true so long as point should jump forward, and
  1019. false when point is at the end of the region.
  1020.  
  1021.    We could use `(forward-word 1)' as the expression for moving point
  1022. forward word by word, but it is easier to see what Emacs identifies as a
  1023. `word' if we use a regular expression search.
  1024.  
  1025.    A regular expression search that finds the pattern for which it is
  1026. searching leaves point after the last character matched.  This means
  1027. that a succession of successful word searches will move point forward
  1028. word by word.
  1029.  
  1030.    As a practical matter, we want the regular expression search to jump
  1031. over whitespace and punctuation between words as well as over the words
  1032. themselves.  A regexp that refuses to jump over interword whitespace
  1033. would never jump more than one word!  This means that the regexp should
  1034. include the whitespace and punctuation that follows a word, if any, as
  1035. well as the word itself.  (A word may end a buffer and not have any
  1036. following whitespace or punctuation, so that part of the regexp must be
  1037. optional.)
  1038.  
  1039.    Thus, what we want for the regexp is a pattern defining one or more
  1040. word constituent characters followed, optionally, by one or more
  1041. characters that are not word constituents.  The regular expression for
  1042. this is:
  1043.  
  1044.      \w+\W*
  1045.  
  1046. The buffer's syntax table determines which characters are and are not
  1047. word constituents.  (*Note What Constitutes a Word or Symbol?: Syntax,
  1048. for more about syntax.  Also, see *Note Syntax: (emacs)Syntax, and,
  1049. *Note Syntax Tables: (elisp)Syntax Tables.)
  1050.  
  1051.    The search expression looks like this:
  1052.  
  1053.      (re-search-forward "\\w+\\W*")
  1054.  
  1055. (Note that paired backslashes precede the `w' and `W'.  A single
  1056. backslash has special meaning to the Emacs Lisp interpreter.  It
  1057. indicates that the following character is interpreted differently than
  1058. usual.  For example, the two characters, `\n', stand for `newline',
  1059. rather than for a backslash followed by `n'.  Two backslashes in a row
  1060. stand for an ordinary, `unspecial' backslash.)
  1061.  
  1062.    We need a counter to count how many words there are; this variable
  1063. must first be set to 0 and then incremented each time Emacs goes around
  1064. the `while' loop.  The incrementing expression is simply:
  1065.  
  1066.      (setq count (1+ count))
  1067.  
  1068.    Finally, we want to tell the user how many words there are in the
  1069. region.  The `message' function is intended for presenting this kind of
  1070. information to the user.  The message has to be phrased so that it
  1071. reads properly regardless of how many words there are in the region: we
  1072. don't want to say that "there are 1 words in the region".  The conflict
  1073. between singular and plural is ungrammmatical.  We can solve this
  1074. problem by using a conditional expression that evaluates different
  1075. messages depending on the number of words in the region.  There are
  1076. three possibilities: no words in the region, one word in the region,
  1077. and more than one word.  This means that the `cond' special form is
  1078. appropriate.
  1079.  
  1080.    All this leads to the following function definition:
  1081.  
  1082.      ;;; First version; has bugs!
  1083.      (defun count-words-region (beginning end)
  1084.        "Print number of words in the region.
  1085.      Words are defined as at least one word-constituent
  1086.      character followed by at least one character that
  1087.      is not a word-constituent.  The buffer's syntax
  1088.      table determines which characters these are."
  1089.        (interactive "r")
  1090.        (message "Counting words in region ... ")
  1091.      
  1092.      ;;; 1. Set up appropriate conditions.
  1093.        (save-excursion
  1094.          (goto-char beginning)
  1095.          (let ((count 0))
  1096.      
  1097.      ;;; 2. Run the while loop.
  1098.            (while (< (point) end)
  1099.              (re-search-forward "\\w+\\W*")
  1100.              (setq count (1+ count)))
  1101.      
  1102.      ;;; 3. Send a message to the user.
  1103.            (cond ((zerop count)
  1104.                   (message
  1105.                    "The region does NOT have any words."))
  1106.                  ((= 1 count)
  1107.                   (message
  1108.                    "The region has 1 word."))
  1109.                  (t
  1110.                   (message
  1111.                    "The region has %d words." count))))))
  1112.  
  1113. As written, the function works, but not in all circumstances.
  1114.  
  1115. * Menu:
  1116.  
  1117. * Whitespace Bug::              The Whitespace Bug in `count-words-region'
  1118.  
  1119.